import React, { useEffect, useState } from 'react';
import NormalWord from '../NormalWord';
import Emoji from '@/utils/Emoji';
import { useTranslation } from 'react-i18next';

import Message from '@/utils/message';
import { sendMessageToRecord } from '@/utils/index';
import { useDispatch, useSelector } from 'react-redux';
import { setChatRecord } from '@/store/reducers/chatRecord';
import { uploadFile } from '@/utils/upload';
import { shareResourceWithFileInfo } from '@/utils/lib';
import WidgetEmoji from '@/utils/Emoji';
import Icon from '@/components/Icon';
import useSyncState from '../hooks/useSyncState';
import AgentServer from '@/modules/Agent';

const Footer = () => {
	const { t } = useTranslation();
	const dispatch = useDispatch();
	const [normalWordView, setNormalWordView] = useSyncState(false);
	const { agent, chatRecord } = useSelector(state => state) as any;

	useEffect(() => {
		document.body.onclick = e => {
			console.log(e, normalWordView());
			if (normalWordView()) {
				setNormalWordView(false);
			}
		};
	}, []);

	const selectEmoji = (event: Event) => {
		event.preventDefault();
		event.stopPropagation();
		Emoji.showEmoji();
	};

	//回车键发送消息
	const keyDown = (event: any) => {
		if (!event.shiftKey && event.keyCode == 13) {
			event.cancelBubble = true;
			event.preventDefault();
			event.stopPropagation();
			sendMessage();
		}
	};

	const sendMessage = () => {
		const messageContent = document.getElementById('widget-message-text')!.innerHTML;
		if (messageContent == '') {
			Message.warning(t('PLEASE_INPUT_MESSAGE'));
			document.getElementById('widget-message-text')!.focus();
			return;
		}
		let content = WidgetEmoji.imgFace2textFace(
			messageContent
				.replace(/<br>/gi, '\n')
				.replace(/<div>/gi, '\n')
				.replace(/&nbsp;/gi, ' ')
				.replace(/<span>/gi, '')
				.replace(/<\/span>/gi, '')
		);
		ivcs.agent.sendTextMessage(
			content,
			'others',
			resp => {
				let data = sendMessageToRecord('text', WidgetEmoji.textFace2imgFace(content), agent);
				console.log(data, '返回数据');
				dispatch(setChatRecord(data));
				console.log('send text message success', resp);
				document.getElementById('widget-message-text')!.innerHTML = '';
			},
			error => {
				console.log('send text message error', error);
				Message.warning(t('send-message-failed'));
			}
		);
	};

	//发送常用语
	const sendNormalWord = (value: string | undefined) => {
		if (value) {
			ivcs.agent.sendTextMessage(
				value,
				'others',
				resp => {
					let data = sendMessageToRecord('text', value, agent);
					console.log(data, '返回数据');
					dispatch(setChatRecord(data));
					console.log('send text message success', resp);
					setNormalWordView(false);
				},
				error => {
					console.log('send text message error', error);
					Message.warning(t('send-message-failed'));
				}
			);
		}
	};

	//发送图片
	const sendImage = async () => {
		let file = document.getElementById('imgfile')!.files[0];
		console.log(file);
		let imgTest = ['png', 'jpg', 'jpeg', 'gif'];
		let index = file.name.lastIndexOf('.');
		let ext = file.name.substr(index + 1).toLowerCase();
		if (imgTest.indexOf(ext) === -1) {
			Message.warning(t('IMAGE_SUPPORT'));
			return;
		}
		if (file.size > AgentServer.configure.maxUploadFileSize) {
			Message.warning(t('FILE_MAX'));
			return;
		}
		let data = await uploadFile(file);
		if (data) {
			try {
				const resp = await shareResourceWithFileInfo('pic', data, 'others');
				let msgData = { ...data, type: 'pic' };
				let messageContent = sendMessageToRecord('link', msgData, agent);
				dispatch(setChatRecord(messageContent));
				Message.normal(t('success'));
			} catch (error) {
				console.log('share resource failed', error);
				Message.warning(t('failed'));
			}
		}
	};

	//发送文件
	const sendFile = async () => {
		let file = document.getElementById('docfile')!.files[0];
		if (file.size > AgentServer.configure.maxUploadFileSize) {
			Message.warning(t('FILE_MAX'));
			return;
		}
		let data = await uploadFile(file);
		if (data) {
			try {
				const resp = await shareResourceWithFileInfo('doc', data, 'others');
				let msgData = { ...data, type: 'doc' };
				let messageContent = sendMessageToRecord('link', msgData, agent);
				dispatch(setChatRecord(messageContent));
				Message.normal(t('success'));
			} catch (error) {
				console.log('share resource failed', error);
				Message.warning(t('failed'));
			}
		}
	};

	return (
		<div className="chat-window-footer-contrainer">
			<div className="chat-window-footer-title">
				<div className="function-box">
					{/*表情icon */}
					<Icon classname="icon-widget-biaoqing" onClick={(e: any) => selectEmoji(e)}></Icon>
					{/*图片icon */}
					<Icon
						classname="icon-widget-tupian"
						onClick={() => {
							document.getElementById('imgfile')?.click();
						}}
					></Icon>
					<input style={{ display: 'none' }} type="file" name="file" id="imgfile" value="" accept="image/gif,image/jpg,image/jpeg,image/png" onChange={sendImage} />
					{/*文件icon */}
					<Icon
						classname="icon-widget-ic_wenjianjia"
						onClick={() => {
							document.getElementById('docfile')?.click();
						}}
					></Icon>
					<input style={{ display: 'none' }} type="file" name="docfile" id="docfile" value="" onChange={sendFile} />
				</div>
				<div className="send-btn-box">
					<button>
						<span onClick={sendMessage}>{t('send')}</span>
					</button>
					<Icon classname="icon-widget-xiajiantou icon" onClick={() => setNormalWordView(!normalWordView())}></Icon>
				</div>
			</div>
			<div className="chat-window-footer-content">
				<div
					contentEditable="true"
					placeholder={t('enter-chat-content') + '...'}
					suppressContentEditableWarning
					id="widget-message-text"
					className="widget-message-text"
					onKeyDown={keyDown}
				></div>
			</div>
			{normalWordView() ? <NormalWord onClick={sendNormalWord} /> : undefined}
		</div>
	);
};

export default Footer;
